package com.ice.work.moment.crawler.strategy;

import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.util.StrUtil;
import com.ice.work.moment.facade.crawler.annotation.HandlerType;
import com.ice.work.moment.facade.crawler.enums.HandlerTypeEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description HandlerProcessor
 * @Author DELL
 * @Create 2019-08-29
 * @Since 1.0.0
 */
@Component
public class HandlerProcessor implements BeanFactoryPostProcessor {
    private final String HANDLER_PACKAGE = "com.ice.work.moment.crawler.service.impl";

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        registerHandlerContext(beanFactory);
    }

    /**
     * 注册 HandlerContext
     * @param beanFactory
     */
    private void registerHandlerContext(final ConfigurableListableBeanFactory beanFactory) {
        Map<Integer, Class> handlerMap = new ConcurrentHashMap(3);
        ClassScanner.scanPackageByAnnotation(HANDLER_PACKAGE, HandlerType.class).forEach(clazz -> {
            HandlerTypeEnum handlerTypeEnum = clazz.getAnnotation(HandlerType.class).value();
            handlerMap.put(handlerTypeEnum.value(), clazz);
        });
        HandlerContext context = new HandlerContext();
        context.setHandlerMap(handlerMap);
        //实现 HandlerContext 单例
        beanFactory.registerSingleton(StrUtil.lowerFirst(HandlerContext.class.getName()), context);
    }
}
